package org.opensuse.bs.ui.actions;

import java.io.File;
import java.util.Vector;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.opensuse.bs.ui.OSC;

public class RemoveLocal implements IObjectActionDelegate {
	private IFile file;
	
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
	}
	
	public void run(IAction action) {
		if(file == null)return;
		if(!MessageDialog.openQuestion(
				null, 
				"Delete action dialog", 
				"Are you really sure?")
				)return;
		final IResource parent = file.getParent();
		final File dir = new File(parent.getLocation().toOSString());
		Job job = new Job("Marking file "+file.getName()+" as deleted") {
			protected IStatus run(IProgressMonitor monitor) {
				try {
					String cmd = "delete "+file.getName();
					Vector<String> result = OSC.run(cmd, null, dir);
					if(result.isEmpty()) {
						return Status.CANCEL_STATUS;
					}
					parent.refreshLocal(IResource.DEPTH_INFINITE, monitor);
				}catch(Exception e) {
					e.printStackTrace();
				}
				return Status.OK_STATUS;
			}
		};
		job.schedule();
	}
	
	public void selectionChanged(IAction action, ISelection selection) {
		if(selection instanceof ITreeSelection) {
			ITreeSelection current = (ITreeSelection) selection;
			Object o = current.getPaths()[0].getLastSegment();
			if(!(o instanceof IFile))return;
			file = (IFile) o;
		}
	}

}
